/*

  The MIT License

  Copyright (c) 2008 - 2011. Dimarik

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

package ru.goodcore.core
{

import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.events.EventDispatcher;
import flash.geom.Rectangle;

import ru.goodcore.display.ui.core.Container;
import ru.goodcore.display.ui.core.UIComponent;
import ru.goodcore.display.ui.core.ui_internal;
import ru.goodcore.utils.ObjectInfo;


[Style(name="paddingTop", type="Number", format="Length", inherit="no")]

[Style(name="paddingBottom", type="Number", format="Length", inherit="no")]

[Style(name="paddingLeft", type="Number", format="Length", inherit="no")]

[Style(name="paddingRight", type="Number", format="Length", inherit="no")]

[Style(name="horizontalAlign", type="String", format="Enum", enumeration="left,center,right", inherit="no")]

[Style(name="verticalAlign", type="String", format="Enum", enumeration="top,middle,bottom", inherit="no")]

[Style(name="gap", type="Number", format="Length", inherit="no")]

/**
 *  @author				Dimarik
 *  @version			1.1
 *  @langversion		3.0
 *  @playerversion		9.0
 * 
 */

public class BoxTracer implements ILayoutTracer {

	//-------------------------------------------------------------------------
	//
	//   Constructor
	//
	//-------------------------------------------------------------------------

	public function BoxTracer() {
		super();
		this._objectInfo = ObjectInfo.getInfo(this);
	}

	//-------------------------------------------------------------------------
	//
	//   Properties
	//
	//-------------------------------------------------------------------------

	private var _objectInfo:	ObjectInfo;

	public function get objectInfo():ObjectInfo {
		return this._objectInfo;
	}

	//-------------------------------------------------------------------------
	//
	//   Private variables
	//
	//-------------------------------------------------------------------------

	private static const _defaultGap:					Number = 1;

	private static const _defaultPaddingLeft:			Number = 0;

	private static const _defaultPaddingRight:			Number = 0;

	private static const _defaultPaddingTop:			Number = 0;

	private static const _defaultPaddingBottom:			Number = 0;


	//-------------------------------------------------------------------------
	//
	//   Private const & variables
	//
	//-------------------------------------------------------------------------

	/**
	 * @private 
	 */
	private const _bounds:	Rectangle = new Rectangle();

	//-------------------------------------------------------------------------
	//
	//   Interface Properties: ILayoutTracer
	//
	//-------------------------------------------------------------------------

	//---------------------------------
	//  target
	//---------------------------------
	/**
	 * @private
	 */
	private var _target:	DisplayObjectContainer;

	public function set target(container:DisplayObjectContainer):void {
		if ( this._target == container )
			return;
		this._target = container;
	}

	public function get target():DisplayObjectContainer {
		return this._target;
	}

	//-------------------------------------------------------------------------
	//
	//   Properties
	//
	//-------------------------------------------------------------------------

	//---------------------------------
	//  horizontal
	//---------------------------------
	/**
	 * @private
	 */	
	private var _horizontal:	Boolean = true;

	public function get horizontal():Boolean {
		return this._horizontal;
	}

	public function set horizontal(value:Boolean):void {
		if (this._horizontal === value)
			return;

		this._horizontal = value;

		if (this._target)
			this.layoutObjects();
	}

	//---------------------------------
	//  paddingTop
	//---------------------------------
	/**
	 * @private
	 */
	private var _paddingTop:	Number = _defaultPaddingTop;

	public function get paddingTop():Number {
		return this._paddingTop;
	}

	public function set paddingTop(value:Number):void {
		if (this._paddingTop === value)
			return;

		this._paddingTop = value;

		if (this._target)
			this.layoutObjects();
	}

	//---------------------------------
	//  paddingBottom
	//---------------------------------
	/**
	 * @private
	 */
	private var _paddingBottom:	Number = _defaultPaddingBottom;

	public function get paddingBottom():Number {
		return this._paddingBottom;
	}

	public function set paddingBottom(value:Number):void {
		if (this._paddingBottom === value)
			return;

		this._paddingBottom = value;

		if (this._target)
			this.layoutObjects();
	}

	//---------------------------------
	//  paddingLeft
	//---------------------------------
	/**
	 * @private
	 */
	private var _paddingLeft:	Number = _defaultPaddingLeft;

	public function get paddingLeft():Number {
		return this._paddingLeft;
	}

	public function set paddingLeft(value:Number):void {
		if (this._paddingLeft === value)
			return;

		this._paddingLeft = value;

		if (this._target)
			this.layoutObjects();
	}

	//---------------------------------
	//  paddingRight
	//---------------------------------
	/**
	 * @private
	 */
	private var _paddingRight:	Number = _defaultPaddingRight;

	public function get paddingRight():Number {
		return this._paddingLeft;
	}

	public function set paddingRight(value:Number):void {
		if (this._paddingRight === value)
			return;

		this._paddingRight = value;

		if (this._target)
			this.layoutObjects();
	}

	//---------------------------------
	//  gap
	//---------------------------------
	/**
	 * @private
	 */
	private var _gap:	Number = _defaultGap;

	public function get gap():Number {
		return this._gap;
	}

	public function set gap(value:Number):void {
		if (this._gap === value)
			return;

		this._gap = value;

		if (this._target)
			this.layoutObjects();
	}

	//---------------------------------
	//  verticalAlign
	//---------------------------------
	/**
	 * @private
	 */
	private var _verticalAlign:	uint = 0;

	public function get verticalAlign():uint {
		return this._verticalAlign;
	}

	public function set verticalAlign(value:uint):void {
		if (this._verticalAlign === value)
			return;

		this._verticalAlign = value;

		if (this._target)
			this.layoutObjects();
	}

	//---------------------------------
	//  horizontalAlign
	//---------------------------------
	/**
	 * @private
	 */
	private var _horizontalAlign:	uint = 0;

	public function get horizontalAlign():uint {
		return this._horizontalAlign;
	}

	public function set horizontalAlign(value:uint):void {
		if (this._horizontalAlign === value)
			return;

		this._horizontalAlign = value;

		if (this._target)
			this.layoutObjects();
	}

	//-------------------------------------------------------------------------
	//
	//   Private properties
	//
	//-------------------------------------------------------------------------
	private function get firstMasterPadding():Number {
		return this._horizontal ? this._paddingLeft : this._paddingTop;
	}

	private function get lastMasterPadding():Number {
		return this._horizontal ? this._paddingRight : this._paddingBottom;
	}

	private function get firstSlavePadding():Number {
		return this._horizontal ? this._paddingTop : this._paddingLeft;
	}

	private function get lastSlavePadding():Number {
		return this._horizontal ? this._paddingBottom : this._paddingRight;
	}

	private function get masterAlign():uint {
		return this._horizontal ? this._horizontalAlign : this._verticalAlign;
	}

	private function get slaveAlign():uint {
		return this._horizontal ? this._verticalAlign : this._horizontalAlign;
	}

	//-------------------------------------------------------------------------
	//
	//   Interface implementation: ILayoutTracer
	//
	//-------------------------------------------------------------------------

	/**
	 * @inheritDoc 
	 */
	public function layoutObjects():Rectangle {
		return this.layout(true);
	}

	/**
	 * @inheritDoc 
	 */
	public function measure():Rectangle {
		return this.layout(false);
	}


	/**
	 * @inheritDoc 
	 */
	public function layout(layout:Boolean = true):Rectangle {

		if ( !this._target )
			return new Rectangle();

		var child:			DisplayObject;
		var uiChild:		UIComponent;
		const uiContainer:	UIComponent = this._target as UIComponent;

		const firstMasterPadding:	Number = this.firstMasterPadding;
		const lastMasterPadding:	Number = this.lastMasterPadding;
		const firstSlavePadding:	Number = this.firstSlavePadding;
		const lastSlavePadding:		Number = this.lastSlavePadding;

		if ( uiContainer ) {
			const list:		Vector.<DisplayObject> = uiContainer.getChildren();
			var len:		uint = list.length;

			if ( !len )
				return new Rectangle();

			const percentChilds:	Vector.<UIComponent> = new Vector.<UIComponent>();

			var masterSize:			Number = 0;
			var slaveSize:			Number = 0;
			var totalPercentSize:	Number = 0;

			masterSize = 0;

			for (var i:uint = 0; i < len; i++) {

				child = list[i];
				uiChild = child as UIComponent;

				if ( !uiChild ) {
					masterSize += this._horizontal ? child.width : child.height;
					masterSize += this._gap;
				} else {

					if ( !uiChild.includeInLayout )
						continue;

					var slavePercentSize:	Number = this._horizontal ? uiChild.percentHeight : uiChild.percentWidth;

					if ( !isNaN(slavePercentSize) ) {
					/*
						var valideSize:Number = Math.floor(
							((this._horizontal ? uiContainer.height : uiContainer.width) -
							firstSlavePadding - lastSlavePadding) * slavePercentSize / 100
						);
					*/

						var valideSize:Number = 
							((this._horizontal ? uiContainer.height : uiContainer.width) -
							firstSlavePadding - lastSlavePadding) * slavePercentSize / 100 ; 

						this._horizontal ? 
							uiChild.ui_internal::valideHeight = valideSize :
							uiChild.ui_internal::valideWidth = valideSize;
					}

					var masterPercentSize:	Number = this._horizontal ? uiChild.percentWidth : uiChild.percentHeight;

					if ( !isNaN(masterPercentSize) ) {
						percentChilds.push(uiChild);
						totalPercentSize += masterPercentSize;
					} else {
						masterSize += this._horizontal ? uiChild.width : uiChild.height;
					}

					masterSize += this._gap;
				}

			}

			len = percentChilds.length;

			if (i) {
				masterSize -= this._gap;

				if (len || !layout) {
					// Есть пропорциональные дети
					// или мы измеряем сколько места займем
					masterSize += firstMasterPadding + lastMasterPadding;
				}
			}

			var restSize:Number = (this._horizontal ? uiContainer.width : uiContainer.height) - masterSize;

			restSize = restSize < 0 ? 0 : restSize;

			if ( len ) {

				if ( totalPercentSize <= 100 ) {
					var ratio:Number = restSize / 100;
				} else {
					ratio = restSize / totalPercentSize;
				}

				for (i = 0; i < len; i++) {
					uiChild = percentChilds[i];

					//valideSize = Math.floor( (this._horizontal ? uiChild.percentWidth : uiChild.percentHeight) * ratio );
					valideSize =  (this._horizontal ? uiChild.percentWidth : uiChild.percentHeight) * ratio;

					this._horizontal ?
						uiChild.ui_internal::valideWidth = valideSize :
						uiChild.ui_internal::valideHeight = valideSize
				}
			}

			len = list.length;

			var masterOffset:	Number = 0;
			
			const masterAlign:	uint = this.masterAlign;
			const slaveAlign:	uint = this.slaveAlign;

			if (masterAlign === 0) {

				masterOffset = firstMasterPadding;

			} else if (masterAlign === 1) {

				if (percentChilds.length) {
					masterOffset = firstMasterPadding;
				} else {
					//masterOffset = (this._horizontal ? uiContainer.width : uiContainer.height) - masterSize;
					masterOffset = restSize >> 1;
				}

			} else {
				masterOffset = (this._horizontal ? uiContainer.width :  uiContainer.height) - masterSize;
				masterOffset -= lastMasterPadding;
			}

			if ( len ) {
				//masterSize = firstMasterPadding;
			} else {
				masterSize = 0;
			}

			for (i = 0; i < len; i++) {
				child = list[i];
				uiChild = child as UIComponent;

				if ( uiChild && !uiChild.includeInLayout ) {
					continue;
				} else {

					layout && (this._horizontal ?
						child.x = masterOffset : 
						child.y = masterOffset);

					masterOffset += this._gap + 
						(this._horizontal ? child.width : child.height);

					var slaveOffset:	Number = 0;

					if (slaveAlign === 0) {
						slaveOffset = firstSlavePadding;
					} else if (slaveAlign === 1) {
						slaveOffset = (this._horizontal ? uiContainer.height - child.height : uiContainer.width - child.width);
						slaveOffset >>= 1;
					} else {
						slaveOffset = (this._horizontal ? uiContainer.height - child.height : uiContainer.width - child.width);
						slaveOffset -= lastSlavePadding;
					}

					layout && (this._horizontal ?
						child.y = slaveOffset : 
						child.x = slaveOffset);

					slaveSize = Math.max(slaveSize, this._horizontal ? child.height : child.width);
				}
			}


			if (i) {
				//masterSize -= this._gap;
				//masterSize += lastMasterPadding;
				slaveSize += firstSlavePadding + lastSlavePadding;
			}

		} else {
			throw new Error('Feature in progress');
		}

		if (this._horizontal) {
			return new Rectangle(0, 0, masterSize, slaveSize);
		} else {
			return new Rectangle(0, 0, slaveSize, masterSize);
		}
	}


}
}